package com.whh.tq.common;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public abstract class AbstractDBHelper {
	public abstract String getTableName();

	public abstract String getCreateTableSQL();

	protected SQLiteDatabase db;

	protected BaseSqliteHelper baseSqliteHelper;

	protected void open(Context context) {
		if (null == db || !this.db.isOpen()) {
			if (baseSqliteHelper == null) {
				baseSqliteHelper = new BaseSqliteHelper(context,AndroidHelper.DB_NAME, null, AndroidHelper.DB_VERSION);
			}
			db = baseSqliteHelper.getWritableDatabase();
		}
	}

	protected void close() {
		if (null != baseSqliteHelper) {
			baseSqliteHelper.close();
		}
		if (null != db && db.isOpen()) {
			db.close();
		}
	}

	protected SQLiteDatabase getDB(Context context) {
		this.open(context);
		return this.db;
	}

	private class BaseSqliteHelper extends SQLiteOpenHelper {

		public BaseSqliteHelper(Context context, String name,CursorFactory factory, int version) {
			super(context, name, factory, version);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(getCreateTableSQL());
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			String sql = "drop table if exists " + getTableName();
			db.execSQL(sql);
			onCreate(db);
		}

	}
}
